<?php
// +----------------------------------------------------------------------
// | ThinkCMF [ WE CAN DO IT MORE SIMPLE ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013-2017 http://www.thinkcmf.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: kane <chengjin005@163.com>
// +----------------------------------------------------------------------
namespace app\user\controller;

use cmf\controller\AdminBaseController;
use cmf\lib\Upload;
use think\Image;

/**
 * 附件上传控制器
 * Class Asset
 * @package app\asset\controller
 */
class AssetController extends AdminBaseController
{
    public function _initialize()
    {
        $adminId = cmf_get_current_admin_id();
        $userId  = cmf_get_current_user_id();
        if (empty($adminId) && empty($userId)) {
            exit("非法上传！");
        }

        config('paginate',[
            'type'      => '\cmf\paginator\Bootstrap2',
            'var_page'  => 'page',
            'list_rows' => 15,
        ]);
    }

    /**
     * webuploader 上传
     */
    public function webuploader()
    {   

        if ($this->request->isPost()) {

            $uploader = new Upload();

            $result = $uploader->upload();

            if ($result === false) {
                $this->error($uploader->getError());
            } else {

                /*处理水印*/
                
                $serWater = $this->request->param('set_water','','trim');

                if( $serWater === '1' ){
                    $uploadPath     = config('upload_path');  //文件上传的根目录
                    $uploadFilePath = $uploadPath.$result['filepath'];  //上传的文件所在路径

                    $image = \think\Image::open($uploadFilePath);

                    //网站水印设置
                    $waterSettings  = cmf_get_option('water_settings');  
                    switch ($waterSettings['water_method']) {
                        // 文字水印
                        case '1':
                            if( !empty($waterSettings['water_zi']) ){
                                $image->text($waterSettings['water_zi'],CMF_ROOT.'font/'.$waterSettings['water_family'],$waterSettings['water_font'],$waterSettings['water_color'],$waterSettings['water_w'],$waterSettings['water_offset'],$waterSettings['water_angle'])->save($uploadFilePath); 
                            }
                            break;
                        default:
                            if( !empty($waterSettings['water_img']) ){
                                $waterImgPath = $uploadPath.$waterSettings['water_img'];  //水印图片所在路径
                                $waterImgInfo = @getimagesize($waterImgPath);             //水印图片信息

                                //若水印图片存在
                                if( file_exists($waterImgPath) ){
                                    $uploadImgInfo  = @getimagesize($uploadFilePath);   //上传的图片信息

                                    //上传的图片宽高大于水印图片宽高时，为上传的图片添加水印
                                    if($uploadImgInfo[0] > $waterImgInfo[0] && $uploadImgInfo[1] > $waterImgInfo[1]){  

                                        // $preview_info  = pathinfo($result['preview_url']);
                                        $image->water($uploadPath.$waterSettings['water_img'],$waterSettings['water_w'],$waterSettings['transparency'])
                                              ->save($uploadFilePath);

                                    }
                                }
                            }

                            break;
                    }
                }

                $this->success("上传成功!", '', $result);
            }

        } else {
            $uploadSetting = cmf_get_upload_setting();

            $arrFileTypes = [
                'image' => ['title' => 'Image files', 'extensions' => $uploadSetting['file_types']['image']['extensions']],
                'video' => ['title' => 'Video files', 'extensions' => $uploadSetting['file_types']['video']['extensions']],
                'audio' => ['title' => 'Audio files', 'extensions' => $uploadSetting['file_types']['audio']['extensions']],
                'file'  => ['title' => 'Custom files', 'extensions' => $uploadSetting['file_types']['file']['extensions']],
                'document' => ['title' => 'Document files','extensions' => $uploadSetting['file_types']['document']['extensions']]
            ];

            $arrData = $this->request->param();

            if (empty($arrData["filetype"])) {
                $arrData["filetype"] = "image";
            }

            $fileType = $arrData["filetype"];

            if (array_key_exists($arrData["filetype"], $arrFileTypes)) {
                $extensions                = $uploadSetting['file_types'][$arrData["filetype"]]['extensions'];
                $fileTypeUploadMaxFileSize = $uploadSetting['file_types'][$fileType]['upload_max_filesize'];
            } else {
                $this->error('上传文件类型配置错误！');
            }

            $assetMenuName = ($fileType == 'image') ? '图片库' : '文件库';
            $this->assign('asset_menu_name', $assetMenuName);

            $this->assign('filetype', $arrData["filetype"]);
            $this->assign('extensions', $extensions);
            $this->assign('upload_max_filesize', $fileTypeUploadMaxFileSize * 1024);
            $this->assign('upload_max_filesize_mb', intval($fileTypeUploadMaxFileSize / 1024));
            $maxFiles  = intval($uploadSetting['max_files']);
            $maxFiles  = empty($maxFiles) ? 20 : $maxFiles;
            $chunkSize = intval($uploadSetting['chunk_size']);
            $chunkSize = empty($chunkSize) ? 512 : $chunkSize;
            $this->assign('max_files', $arrData["multi"] ? $maxFiles : 1);
            $this->assign('chunk_size', $chunkSize); //// 单位KB
            $this->assign('multi', $arrData["multi"]);
            $this->assign('app', $arrData["app"]);

            $size = $this->request->param('size',20);
            $this->assign('size',  $size);

            $setWaterOn  = 1;//显示水印设置
            $no_material = $this->request->param('no_material',0);  //1为不需要资源库
            $water       = $this->request->param('water',0);        //是否为上传水印图片
            $upload_type = $this->request->param('upload_type',0);

            // 当为上传水印图片时,不需要资源库和水印设置
            if( $water==1 || $upload_type==1 || $fileType!='image' ){
                // $no_material = 1;
                $setWaterOn  = 0;
            }


            // pre($no_material,1);
            $this->assign('no_material', $no_material);     //是否显示素材库菜单
            $this->assign('set_water_on', $setWaterOn);     //是否显示水印设置

            return $this->fetch(":webuploader");
        }
    }

    /**
     * 删除文件
     */
    public function deleteAssetData(){

        if ($this->request->isPost()) {

            $param = $this->request->param();
            // pre($param,1);
            $uploadPath = config('upload_path');

            if (isset($param['id'])) {
                $id = $this->request->param('id');
                
                $file_path = db('asset')->where('id',$id)->value('file_path');
                @unlink($uploadPath.$file_path);
                $res = db('asset')->where('id',$id)->delete();
            }

            if (isset($param['ids'])) {
                $ids = $this->request->param('ids/a');
                
                $list = db('asset')->where('id','in',$ids)->column('file_path');
                foreach ($list as $k => $v) {
                    @unlink($uploadPath.$v);
                }
                $res = db('asset')->where('id','in',$ids)->delete();
            }

            
            $result = array(
                'status'  => 1,
                'message' => '删除成功',
            );
            return $result;
        }

        exit();

    }


    /**
     * 读取数据库素材记录
     */
    public function getAssetData()
    {
        $filter   = $this->request->param();
        $page     = $this->request->param('page',1);      //页码
        $size     = $this->request->param('size',10);    //每页的数据条数
        $fileType = $this->request->param('type','','trim');    //文件类型

        $uploadPath = config('upload_path');

        $imageExt = explode(',', 'jpg,jpeg,png,gif,bmp4');

        $where    = [];
        if( $fileType =='image' ){
            $where['suffix'] = ['in',$imageExt];
        }else{
            $where['suffix'] = ['not in',$imageExt];
        }

        $fileImg = cmf_get_image_url('static/js/webuploader/image-upload/f.png');

        $keyword = empty($filter['keyword']) ? '' : $filter['keyword'];
        if (!empty($keyword)) {
            $where['filename'] = ['like', "%$keyword%"];
        }

        $list = db('asset')
             -> field('id, file_size, filename, file_path, suffix')
             -> where($where)
             -> order('create_time desc')
             -> paginate($size)
             -> appends($filter);
        // pre( db('asset')->getLastSql() );

        foreach ($list as $k => $v) {
            // 若文件类型为图片，直接输出
            if (in_array($v['suffix'], $imageExt)) {
                $v['thumb_img'] = '/static/images/default-thumbnail.png';
                if( file_exists($uploadPath. iconv('gb2312','UTF-8',$v['file_path'])) ){
                    $v['thumb_img'] = '/'.$uploadPath.$v['file_path'];
                }
            }else{
                // 否则根据文件扩展名获取对应图标
                $v['thumb_img'] = $this->ext_filter($v['suffix']);
            }
            $v['file_size'] = format_bytes($v['file_size']);

            $dataList[] = $v;
        }


        $this->assign('upload_path', $uploadPath);
        
        // $this->assign('list', $list->items());
        $this->assign('list', $dataList);
        $this->assign('page', $list->render());
        $this->assign('filetype', $fileType);

        $html = $this->fetch('admin_asset/asset_data_ajax');

        $result = [
            'status' => 1,
            'html'   => $html
        ];

        return $result;
    }

    
    //文件列表
    private function ext_filter($file_ext) {
        $file = '';
        switch ($file_ext) {
            case 'flac': $file = 'static/images/file/flac.png'; break;
            case 'fla': $file  = 'static/images/file/fla.png'; break;
            case 'tif': 
            case 'tiff':$file  = 'static/images/file/tiff.png'; break;
            case 'mdb': 
            case 'accdb':$file = 'static/images/file/accdb.png'; break;
            case 'rar': $file  = 'static/images/file/rar.png'; break;
            case 'zip': $file  = 'static/images/file/zip.png'; break;
            case 'xlsx':
            case 'xls': $file  = 'static/images/file/xlsx.png'; break;
            case 'pptx':
            case 'ppt': $file  = 'static/images/file/pptx.png'; break;
            case 'doc':
            case 'docx':$file  = 'static/images/file/docx.png'; break;
            case 'wmv': $file  = 'static/images/file/wmv.png'; break;
            case 'wav': $file  = 'static/images/file/wav.png'; break;
            case 'txt': $file  = 'static/images/file/text.png'; break;
            case 'pub': $file  = 'static/images/file/pub.png'; break;
            case 'psd': $file  = 'static/images/file/psd.png'; break;
            case 'pdf': $file  = 'static/images/file/pdf.png'; break;
            case 'mp4': $file  = 'static/images/file/mp4.png'; break;
            case 'mp3': $file  = 'static/images/file/mp3.png'; break;
            case 'mov': $file  = 'static/images/file/mov.png'; break;
            case 'midi':$file  = 'static/images/file/midi.png'; break;
            case 'jsf': $file  = 'static/images/file/jsf.png'; break;
            case 'ini': $file  = 'static/images/file/ini.png'; break;
            case 'html':$file  = 'static/images/file/html.png'; break;
            case 'css': $file  = 'static/images/file/css.png'; break;
            case 'avi': $file  = 'static/images/file/avi.png'; break;
            default: $file = 'static/images/file/systeme.png';
        }
        $file = '/'.$file;
        return $file;
    }


    /**
     *  获取文件
     */
    // public function select_file(){
    //     //缓存所有用户上传的文件信息
    //     $assetArr = cache('assetArr');
    //     if( empty($assetArr) ){
    //         $asset = db('asset')->field('create_time,filename,file_path,file_key')->select()->toArray();
    //         foreach ($asset as $k => $v) {
    //             $assetArr[$v['file_key']] = $v;
    //         }
    //         cache('assetArr',$assetArr);
    //     }

    //     if ($this->request->isPost()) {
    //         $name     = $this->request->param('name','','trim');    //要读取的目录
    //         $filetype = $this->request->param('type','','trim');    //文件类型
    //         $page     = $this->request->param('page',1);            //页码
    //         $size     = $this->request->param('size',100);            //每页的数据条数
    //         // $size = 30;

    //         //要读取的目录完整路径
    //         $dir = $uploadPath = config('upload_path');   //文件上传的根目录
    //         if( !empty($name) ){
    //             $dir  .= $name.'/';
    //         }

    //         //读取目录下的文件
    //         $file_data = cmf_get_file_list($dir,$filetype);

    //         //若不是根目录，获取目录面包屑
    //         $crumbs = '';
    //         $crumbs_dir  = array_filter( explode('/', $name) );
    //         if( !empty($crumbs_dir) ){
    //             //遍历组成目录面包屑
    //             $select_file = '';
    //             foreach ($crumbs_dir as $k => $v) {
    //                 $select_file.='/'.$v;
    //                 $select_file = trim($select_file, '/');
    //                 $crumbs .= '<dd data-name="'.$v.'" onClick="select_file('."'".$select_file."'".',1)" >'."&nbsp;&nbsp;/&nbsp;&nbsp;<a href='javascript:;'>".$v.'</a></dd>';
    //             }
    //         }
    
    //         $html = '';
    //         //目录下没有文件夹和文件
    //         if(empty($file_data['folder']) && empty($file_data['file'])){
    //             $noDataImg = cmf_get_image_url('/static/js/webuploader/image-upload/no_record.png');
    //             $html .= '<div class="no_record"><img src="'.$noDataImg.'" width="100" /><p class="no_tit">没有相关文件！</p></div>';
    //         }else{
    //             //遍历文件夹
    //             if(!empty($file_data['folder'])){
    //                 $html ="<div class='file_folder clearfix'>";

    //                 foreach($file_data['folder'] as $key=>$val){
    //                     $kk = $key+1;
    //                     $folder_name = empty($name)? $val : $name.'/'.$val ;
    //                     $html.= '<dl title="'.$val.'" class="file-item file-item-dir dir-item-"'.$kk.'" data-id="'.$kk.'" data-name="'.$folder_name.'" onClick="select_file('."'".$folder_name."'".')" >'.
    //                     '<dt class="dir-bg"></dt><dd>'.$val.'</dd></dl>';
    //                 }

    //                 $html.="</div>";
    //             }

    //             //遍历文件
    //             if( !empty($file_data['file']) ){

    //                 $count      = count($file_data['file']);
    //                 $count_page = ceil($count/$size);

    //                 // 根据页码，得到数据开始和结束的键值下标
    //                 $start_key = $page*$size-$size;
    //                 $end_key   = $page*$size;

    //                 $html .="<div class='file_file clearfix'>";

    //                 $dow_name = ($filetype == 'image') ? '预览' : '下载';

    //                 foreach($file_data['file'] as $key=>$val){
    //                     //只获取对应下标的数据
    //                     if( $key >= $start_key && $key < $end_key ){
    //                         $file_path = !empty($name) ? $name.'/'.$val['file'] : $val['file'] ;

    //                         //获取文件上传时的原文件名
    //                         $SaveFilePath = './'.$uploadPath.$file_path;
    //                         @$file_md5     = md5_file($SaveFilePath);
    //                         @$file_sha1    = sha1_file($SaveFilePath);
    //                         @$file_key     = $file_md5 . md5($file_sha1);

    //                         $file_name = $val['file'];
    //                         if( $assetArr[$file_key] ){
    //                             $file_info = $assetArr[$file_key];
    //                             $file_name =  str_replace(' ', '', $file_info['filename']);
    //                             // echo $file_name;die;
    //                         }

    //                         if($filetype =='image'){
    //                             $html.="<dl class='file-item file-item-file dir-item' onClick='file_click(this)' >".
    //                                 "<dt><img src='".cmf_get_image_url($file_path)."'/></dt><dd class='hid_name'>".$file_name."</dd>".
    //                                 "<div class='oper'><a href='javascript:;' class='item-preview' data-title='".$file_path."' onClick='view_img(this);'>".$dow_name."</a><a href='javascript:;' class='item-del' data-title='".$file_path."' onClick='del_img(this)'>删除</a></div><input type='hidden' class='hid_url' value='".$val['url']."' /><input type='checkbox' name='img_select[]' value='' class='item-checkbox'/></dl>";
    //                         }else{
    //                             $fileImg = cmf_get_image_url('/static/js/webuploader/image-upload/f.png');
    //                             $html.="<dl title=".$file_name." class='file-item file-item-file dir-item' onClick='file_click(this)' >".
    //                                 "<dt><img src='".$fileImg."'/></dt><dd class='hid_name'>".$file_name."</dd>".
    //                                 "<div class='oper'><a href='".cmf_get_image_url($file_path)."' class='item-preview' target='_blank' >".$dow_name."</a><a href='javascript:;' class='item-del' data-title='".$file_path."' onClick='del_img(this)' >删除</a></div><input type='hidden' class='hid_url' value='".$val['url']."' /><input type='checkbox' name='img_select[]' value='' class='item-checkbox'/></dl>";
                              
    //                         }
    //                     }
    //                 }

    //                 $html .="</div>";
    //             }
    //         }

    //         $pagination = page($page,$count,$size,5);   //生成分页信息
    //         $result = array(
    //             'html'       => $html,          //数据集
    //             'crumbs'     => $crumbs,        //目录面包屑
    //             'pagination' => $pagination,    //分页信息
    //         );

    //         return $result;
    //     }
    // }
}


